package com.example.demo.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author : 叶荻风
 * @create : 2024/5/23 10:30
 */
public class TestCglib {
    public static void main(String[] args) {
        //创建原始对象
        UserService userService = new UserService();

        //通过CGLIB创建动态代理
        //Enhancer.create() 代理
        //JDK proxy.newProxyInstance(classloder,interfaces,invacatiohandler)
        // Enhancer.setClassLoader
        //Enhancer.setSuperClass
        //Enhancer.setCallback

        Enhancer enhancer = new Enhancer();
        enhancer.setClassLoader(TestCglib.class.getClassLoader());
        enhancer.setSuperclass(UserService.class);

        MethodInterceptor methodInterceptor = (obj, method, args1, proxy) -> {
            System.out.println("cglib log");
            Object ret = method.invoke(userService, args1);
            System.out.println("cglib log");
            return ret;
        };
        enhancer.setCallback(methodInterceptor);
        UserService userServiceProxy = (UserService) enhancer.create();
        userServiceProxy.login("suns","123456");
    }
}
